#!/bin/bash

SUDO="sudo "
if [[ $(id -u) -eq 0 ]]; then SUDO=""; fi

read -p "Enter golang version (default 1.22.5): " version </dev/tty
version=$(echo "$version" | tr -s '[:space:]')
if [[ "$version" == "" ]]; then version="1.22.5"; fi

$SUDO mkdir -p /opt/go/${version}

if [[ -x /opt/go/$version/bin/go ]]; then
    read -p "golang[${version}] is installed, reinstall it? (y/N) " reinstall </dev/tty
    reinstall=$(echo "$reinstall" | tr -s '[:space:]')
    if [[ "$reinstall" != [Yy] ]]; then exit 0; fi
fi
$SUDO rm -rf /opt/go/${version}/*

if [[ ! -f go${version}.linux-amd64.tar.gz ]]; then
    wget https://golang.google.cn/dl/go${version}.linux-amd64.tar.gz
fi
if [[ ! -f go${version}.linux-amd64.tar.gz ]]; then echo "download failed."; exit -1; fi

$SUDO tar -zxvf go${version}.linux-amd64.tar.gz -C /opt/go/${version} --strip-components=1
rm -f go${version}.linux-amd64.tar.gz

echo -e "\nMake sure that the following content exists in the \$HOME/.bashrc"
echo -e "\texport GOHOME=/opt/go/${version}"
echo -e "\texport GOPATH=/opt/go/${version}/path"
echo -e "\texport GOPROXY=https://goproxy.cn,direct"
echo -e "\texport PATH=\$GOHOME/bin:\$PATH"
